/****************************************************************************
**
** Copyright (C) 2009 Alexander Solis.
**
** This file is part of Alejandria
** Alejandria is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** Alejandria is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Alejandria.  If not, see <http://www.gnu.org/licenses/>.
**
****************************************************************************/

#include <QtGui>
#include <QMessageBox>

#include <model/library.h>

#include <view/newbookdialog/newbookdialog.h>
#include <view/aboutdialog/aboutdialog.h>

#include "mainwindow.h"
#include "categorydelegate.h"
#include "subcategorydelegate.h"
#include "statusdelegate.h"
#include "owndelegate.h"
#include "loaneddelegate.h"
#include "ratingdelegate.h"

MainWindow::MainWindow (QWidget *parent, Library &lib)
	: QMainWindow(parent),
	library(lib)
{
	setupUi(this);
	
    newBookDialog   = NULL;
    aboutDialog     = NULL;

	setupActions();
	createToolBars();
	createStatusBar();
	createDelegates();
	
    readSettings();
	
	setupTable();	
	setupFilter();

    show();
}

void MainWindow::closeEvent(QCloseEvent *event)
{
        writeSettings();
}

void MainWindow::newBookSlot ()
{
    if (!newBookDialog) {
        newBookDialog = new NewBookDialog(this);
        connect(newBookDialog, SIGNAL(addBookSignal (QString, QString, QString, QString, QString, QString, int, bool, QString)), this, SLOT(addBookSlot(QString, QString, QString, QString, QString, QString, int, bool, QString)));
    }

    newBookDialog->show();
    newBookDialog->raise();
    newBookDialog->activateWindow();
}

void MainWindow::showAbout()
{
    if (!aboutDialog) {
        aboutDialog = new AboutDialog(this);
    }

    aboutDialog->show();
    aboutDialog->raise();
    aboutDialog->activateWindow();
}

void MainWindow::addBookSlot (QString id, QString title, QString author, QString category, QString status, QString own, int rating, bool loaned, QString comments)
{
    if (!library.insertData(id, title, author, category, status, own, rating, loaned, comments))
       	QMessageBox::information(this, tr("Add book failed"), tr("An error has ocurred and it was not possible to add your book.\nIt is possible that the ISBN is repeated, please check if you entered the correct ISBN for the new book."));
}

void MainWindow::deleteBookSlot()
{
    if (QMessageBox::question(this, 
                              tr("Delete the book?"), 
                              tr("Click 'Yes' to completely remove the selected book from your library.\nClick 'No' to keep the book."),
                              QMessageBox::Yes, QMessageBox::No) 
                              == QMessageBox::Yes)
	    library.deleteData(tableView->currentIndex().row());
}

void MainWindow::setupActions ()
{
 	connect(actionNewBook,      SIGNAL(triggered()),                this,           SLOT(newBookSlot()));
	connect(actionDeleteBook,   SIGNAL(triggered()),                this,           SLOT(deleteBookSlot()));
    connect(actionExit,         SIGNAL(triggered()),                this,           SLOT(close()));
    connect(categoryComboBox,   SIGNAL(activated(const QString &)), &library,       SLOT(filter(const QString &)));
    connect(searchLineEdit,     SIGNAL(textChanged(const QString&)),&library,       SLOT(search(const QString &)));
    connect(clearSearchButton,  SIGNAL(released()),                 searchLineEdit, SLOT(clear()));
    connect(actionAbout,        SIGNAL(triggered()),                this,           SLOT(showAbout()));
}

void MainWindow::createToolBars ()
{
    fileToolBar = addToolBar(tr("&File"));
    fileToolBar->addAction(actionNewBook);
	fileToolBar->addAction(actionDeleteBook);

    fileToolBar = addToolBar(tr("&Search"));
    fileToolBar->addWidget(searchFilterFrame);
}

void MainWindow::createStatusBar () 
{
	statusBar()->showMessage(tr("Ready"));
}

void MainWindow::createDelegates ()
{
	categoryDelegate    = new CategoryDelegate(this);
	statusDelegate      = new StatusDelegate(this);
	ownDelegate         = new OwnDelegate(this);
	loanedDelegate      = new LoanedDelegate(this);
	ratingDelegate      = new RatingDelegate(this);	
}

void MainWindow::readSettings ()
{
    QSettings settings("MellonTec", "OpenBooks");
    restoreGeometry(settings.value("geometry").toByteArray());
}

void MainWindow::writeSettings ()
{
    QSettings settings("MellonTec", "OpenBooks");
    settings.setValue("geometry", saveGeometry());
}

void MainWindow::setupTable ()
{
	tableView->setModel(library.getSqlTableModel());
	
    tableView->setItemDelegateForColumn(Category,   categoryDelegate);
	tableView->setItemDelegateForColumn(Status,     statusDelegate);
	tableView->setItemDelegateForColumn(Own,        ownDelegate);
	tableView->setItemDelegateForColumn(Rating,     ratingDelegate);
	tableView->setItemDelegateForColumn(Loaned,     loanedDelegate);

    tableView->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
    tableView->horizontalHeader()->setStretchLastSection(true);
    tableView->resizeColumnsToContents();
    tableView->setSortingEnabled(true); 
}

void MainWindow::setupFilter ()
{
    QStringList comboData;
    comboData << "Show All" << "Computer science, information & general works"  << "Philosophy and psychology"  << "Religion"  << "Social sciences"  
        << "Language"  << "Science"  << "Technology"  << "Arts and recreation"  << "Literature"  << "History, geography and biography";
    categoryComboBox->addItems(comboData);
}